<template>
  <div>
    <a-card>
      <div class="tips">
        <div class="tips-title">{{ tips.inviteName }}</div>
        <div class="tips-content">有效期：{{ tips.startTime }} 至 {{ tips.endTime }}</div>
      </div>
      <!-- 搜索模块 -->
      <a-row type="flex" class="search-content" justify="space-between" style="margin-bottom: 20px">
        <a-col>
          <a-select
            v-model:value="searchStatus"
            style="width: 120px"
            ref="select"
            @change="resetPage"
          >
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option :value="2">已使用</a-select-option>
            <a-select-option :value="1">未使用</a-select-option>
            <a-select-option :value="0">已作废</a-select-option>
          </a-select>
        </a-col>
        <a-col>
          <a-range-picker v-model:value="searchTimeHorizon" @change="resetPage" />
          <a-input-search
            v-model:value="searchValue"
            placeholder="搜索员工名称"
            class="search-module_input"
            style="width: 160px; margin: 0 20px"
            @search="resetPage"
          ></a-input-search>
          <a-button type="primary" style="margin: 0 20px" @click="addInviteCode">
            生成邀请码
          </a-button>
          <a-button type="primary" @click="exportCodeLibrary">导出</a-button>
        </a-col>
      </a-row>
      <!-- 列表数据 -->
      <a-table
        :loading="data.loading"
        :columns="columns"
        :data-source="data.dataSource"
        :pagination="false"
        rowKey="codeId"
      >
        <template #handler="{ record }">
          <a v-if="record.status === 1" @click="confirmEditInviteCodeLose(record.codeId)">作废</a>
          <a v-else>--</a>
        </template>
        <template #orderSnStr="{ record }">
          {{ record.orderSnStr[0] || '-' }}
        </template>
      </a-table>
      <a-row style="margin-top: 20px" type="flex" justify="end">
        <a-col>
          <a-pagination
            show-quick-jumper
            showSizeChanger
            v-model:pageSize="pagination.pageSize"
            v-model:current="pagination.current"
            :total="pagination.total"
            :showTotal="() => `共 ${pagination.total} 条数据`"
            @change="getList"
            @showSizeChange="getList"
          />
        </a-col>
      </a-row>
    </a-card>
    <!-- 抽屉表单 -->
    <a-drawer
      v-model:visible="showCodeForm.visible"
      :title="showCodeForm.title"
      :width="800"
      @close="closeCodeForm"
    >
      <a-form
        ref="codeFormRef"
        :model="codeForm"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="每人所需数量" name="number">
          <a-input-number v-model:value="codeForm.number" :min="1" />
        </a-form-item>
        <a-form-item label="绑定员工" name="userId">
          <a-popconfirm
            placement="right"
            ok-text="添加"
            cancel-text="取消"
            @confirm="validUserForm"
            @visibleChange="cancelAddUser"
          >
            <template #icon><div></div></template>
            <template #title>
              <a-form
                ref="userFormRef"
                :model="userForm"
                :label-col="{
                  span: 6,
                }"
                :wrapper-col="{
                  span: 18,
                }"
              >
                <a-form-item label="用户名" name="nickName">
                  <a-input v-model:value="userForm.nickName"></a-input>
                </a-form-item>
                <a-form-item label="手机号" required name="phonenumber">
                  <a-input v-model:value="userForm.phonenumber"></a-input>
                </a-form-item>
              </a-form>
            </template>
            <a-button>添加员工</a-button>
          </a-popconfirm>
          <a-transfer
            :title="['', '']"
            :data-source="userData.dataSource"
            show-search
            :list-style="{
              width: '250px',
              height: '300px',
            }"
            :operations="['选择添加', '移除所选']"
            :rowKey="record => record.userId"
            :target-keys="codeForm.userId"
            :render="item => `${item.nickName}`"
            :filterOption="() => true"
            @search="confirmGetUserList"
            @change="handleChange"
          >
            <template #notFoundContent>
              <span>没数据</span>
            </template>
          </a-transfer>
        </a-form-item>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-button style="margin-right: 8px" @click="closeCodeForm">取消</a-button>
        <a-button type="primary" :loading="loading" :disabled="loading" @click="onSubmit">
          确定生成
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
const columns = [
  {
    title: '邀请码',
    dataIndex: 'code',
  },
  {
    title: '绑定员工',
    dataIndex: 'nickName',
  },
  {
    title: '手机号',
    dataIndex: 'phonenumber',
  },
  {
    title: '创建时间',
    dataIndex: 'createTimeStr',
  },
  {
    title: '使用时间',
    dataIndex: 'useTimeStr',
  },
  {
    title: '使用店铺',
    dataIndex: 'shopName',
  },
  {
    title: '订单号',
    dataIndex: 'orderSnStr',
    slots: {
      customRender: 'orderSnStr',
    },
  },
  {
    title: '状态',
    dataIndex: 'statusVal',
    slots: {
      customRender: 'statusVal',
    },
  },
  {
    title: '操作',
    dataIndex: 'handler',
    slots: {
      customRender: 'handler',
    },
  },
];
import { ref, defineComponent, reactive, toRaw } from 'vue';
import { message } from 'ant-design-vue';
import { useRoute } from 'vue-router';
import {
  apiGetInviteCodeList,
  apiCreateInvideCode,
  apiEditInvideCodeLose,
  apiGetInviteDetail,
  apiExportInvideCodeLibrary,
} from '@/api/marketSetting/inviteAcitve';
import { concatIds } from '@/utils/helper';
import { apiGetUserList, apiAddUser } from '@/api/common';
import { downloadFile, parseTime } from '@/utils';
const transList = list => {
  return list.map(item => {
    item.createTimeStr = parseTime(item.createTime);
    item.useTimeStr = (item.useTime && parseTime(item.useTime)) || '-';
    item.shopName = item.shopName || '-';
    item.orderSnStr = item.shopOrderVoList.map(order => order.orderSn);
    return item;
  });
};
export default defineComponent({
  name: '',
  setup() {
    const route = useRoute();
    const inviteId = route.params.inviteId;

    // 搜索时间范围
    const searchTimeHorizon = ref([]);

    // 搜索活动名称
    const searchValue = ref('');
    // 搜索状态
    const searchStatus = ref('');

    // 列表数据
    const data = reactive({
      loading: false,
      dataSource: [],
    });

    // 分页数据
    const pagination = reactive({
      total: 0,
      current: 1,
      pageSize: 10,
    });

    const disposeTime = () => {
      const useStartTime =
        searchTimeHorizon.value[0] &&
        searchTimeHorizon.value[0]._d &&
        searchTimeHorizon.value[0]._d.getTime();

      const useEndTime =
        searchTimeHorizon.value[1] &&
        searchTimeHorizon.value[1]._d &&
        searchTimeHorizon.value[1]._d.getTime();

      return {
        useStartTime,
        useEndTime,
      };
    };

    /**
     * 获取码库列表
     **/
    const getList = async () => {
      data.loading = true;
      const { useStartTime, useEndTime } = disposeTime();
      try {
        // const res = await apiGetInviteCodeList({
        //   pageNum: pagination.current,
        //   pageSize: pagination.pageSize,
        //   status: searchStatus.value,
        //   like: searchValue.value,
        //   useStartTime,
        //   useEndTime,
        //   inviteId,
        // });
        // data.dataSource = transList(res.data.rows);
        // pagination.total = res.data.total;
        const { pageInfo } = await apiGetInviteCodeList({
          pageNum: pagination.current,
          pageSize: pagination.pageSize,
          status: searchStatus.value,
          like: searchValue.value,
          useStartTime,
          useEndTime,
          inviteId,
        });
        data.dataSource = transList(pageInfo.list);
        pagination.total = pageInfo.total;
      } finally {
        data.loading = false;
      }
    };
    getList();

    /**
     * 抽屉初始值
     **/
    const showCodeForm = ref({
      visible: false,
      title: '',
    });

    const tips = reactive({
      inviteName: '',
      startTime: '',
      endTime: '',
    });
    /**
     * 获取邀请码活动详情
     **/
    const confirmGetInviteDetail = () => {
      apiGetInviteDetail({ inviteId }).then(res => {
        const { sysInvite } = res;
        tips.inviteName = sysInvite.inviteName;
        tips.startTime = parseTime(sysInvite.startTime);
        tips.endTime = parseTime(sysInvite.endTime);
        // const { data } = res;
        // tips.inviteName = data.inviteName;
        // tips.startTime = parseTime(data.startTime);
        // tips.endTime = parseTime(data.endTime);
      });
    };
    confirmGetInviteDetail();

    /**
     * 显示邀请码抽屉
     **/
    const addInviteCode = () => {
      showCodeForm.value.visible = true;
      showCodeForm.value.title = '生成邀请码';
    };

    // 表单组件
    const codeFormRef = ref();
    // 表单初始值
    const codeForm = reactive({
      number: '',
      userId: [],
    });

    /**
     * 表单校验规则
     **/
    const rules = {
      number: [
        {
          required: true,
          message: '所需数量不能为空',
          trigger: 'blur',
          type: 'number',
        },
      ],
      userId: [
        {
          required: true,
          trigger: 'change',
          message: '所选员工不能为空',
          type: 'array',
        },
      ],
    };

    /**
     * 提交表单
     **/
    const onSubmit = () => {
      codeFormRef.value
        .validate()
        .then(() => {
          confirmCreateInviteCode();
        })
        .catch(error => {
          console.log('error', error);
        });
    };

    /**
     * 生成邀请码
     **/
    const loading = ref(false);
    const confirmCreateInviteCode = async () => {
      const { number, userId } = codeForm;
      let userIdMap = concatIds(userId);
      loading.value = true;

      try {
        await apiCreateInvideCode({
          userId: userIdMap,
          number,
          inviteId,
        });
        closeCodeForm();
        getList();
        message.success('成功生成邀请码');
      } finally {
        loading.value = false;
      }
    };

    /**
     * 重置表单
     **/
    const resetForm = () => {
      codeFormRef.value.resetFields();
      codeForm.number = '';
      codeForm.userId = [];
    };

    // 员工列表
    const userData = reactive({
      dataSource: [],
    });
    const confirmGetUserList = async (direction, like = '') => {
      try {
        const { adminUser } = await apiGetUserList({ like });
        userData.dataSource = adminUser;
        // const { data } = await apiGetUserList({ like });
        // userData.dataSource = data;
      } catch (error) {
        console.log(error);
      }
    };
    confirmGetUserList();

    /**
     * 穿梭框更改事件
     **/
    const handleChange = keys => {
      codeForm.userId = keys;
    };

    /**
     * 关闭表单
     **/
    const closeCodeForm = () => {
      showCodeForm.value.visible = false;
      resetForm();
    };

    /**
     * 新增用户表单初始值
     **/
    const userForm = reactive({
      nickName: '',
      phonenumber: '',
    });

    // 员工表单
    const userFormRef = ref();

    /**
     * 校验表单
     **/
    const validUserForm = () => {
      userFormRef.value
        .validate()
        .then(() => {
          confirmAddUser();
        })
        .catch(error => {
          if (error.errorFields && error.errorFields.length) {
            message.error('请输入手机号');
          }
        });
    };

    /**
     * 添加员工
     **/
    const confirmAddUser = () => {
      apiAddUser(toRaw(userForm)).then(() => {
        message.success('新增成功');
        confirmGetUserList();
      });
    };

    /**
     * 取消添加员工
     **/
    const cancelAddUser = v => {
      setTimeout(() => {
        if (!v) {
          userForm.nickName = '';
          userForm.phonenumber = '';
          userFormRef.value.resetFields();
        }
      }, 500);
    };

    /**
     * 作废邀请码
     **/
    const confirmEditInviteCodeLose = codeId => {
      apiEditInvideCodeLose({ codeId }).then(() => {
        getList();
        message.success('已作废');
      });
    };

    /**
     * 获取列表重置页码
     **/
    const resetPage = () => {
      pagination.current = 1;
      getList();
    };

    /**
     * 导出码库
     **/
    const exportCodeLibrary = () => {
      const { useStartTime, useEndTime } = disposeTime();
      apiExportInvideCodeLibrary({
        inviteId,
        status: searchStatus.value,
        useStartTime,
        useEndTime,
        like: searchValue.value,
      }).then(res => {
        downloadFile(res, { fileName: `邀请码导出-${parseTime(new Date())}` });
      });
    };

    return {
      columns,
      data,
      getList,
      searchStatus,
      searchTimeHorizon,
      searchValue,
      addInviteCode,
      showCodeForm,
      codeFormRef,
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 20,
      },
      other: '',
      codeForm,
      rules,
      onSubmit,
      resetForm,
      userData,
      handleChange,
      closeCodeForm,
      userForm,
      userFormRef,
      validUserForm,
      cancelAddUser,
      confirmGetUserList,
      confirmEditInviteCodeLose,
      pagination,
      resetPage,
      tips,
      loading,
      exportCodeLibrary,
    };
  },
});
</script>
<style lang="less">
.tips {
  width: 370px;
  height: 60px;
  margin-bottom: 18px;
  padding: 5px;
  background-color: #d7d7d7;
  &-title {
    color: #333;
    font-size: 14px;
  }
  &-content {
    color: #aaa;
    font-size: 14px;
  }
}
.search-content {
  margin-bottom: 20px;
}
</style>
